import React, { Component } from 'react';
import fetch from 'dva/fetch';
import { Form, Row, Col, Button, InputNumber, Select, Spin } from 'antd';
import reactComponentDebounce from 'react-component-debounce';
import StaticEditTable from '../../Common/StaticEditTable/StaticEditTable';
import styles from '../../../index.less';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';


const InputNumberA = reactComponentDebounce(800)(InputNumber);
const FormItem = Form.Item;
const { Option } = Select;

class TabFinancePeriodComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sTabId: props.app.currentPane.key, /* 当前标签 */
      componentName: props.componentName, /* 组件名 */
      masterConfig: props.masterConfig, /* 配置 */
      formData: props.formData, /* 配置 */
      sActiveId: props.sActiveId, /* 窗体Id */
      disabled: props.disabled, /* 是否是查看状态 */
      sId: props.sId, /* 业务数据Id */
      financeConfig: [], /* 会计期间表配置 */
      headerConfig: [], /* 表头配置 */
      iYear: props.iYear,
      tTabStartDate: '1',
      financeId: '',
      loading: false,
      finDisabled: false,
    };
  }

  componentWillMount() {
    /* 获取表数据 */
    const {
      masterConfig, formData, sActiveId, sId, sTabId, componentName, iYear,
    } = this.state;
    const { dispatch } = this.props;
    const financeTable = formData.filter(item => (item.sTbName.toLowerCase() === 'sysaccountperiod'))[0];
    const financeConfig = financeTable.gdsconfigformslave;
    /* 主表配置 */
    const financeId = masterConfig.sId;
    /* 表Id */
    const value = {
      sSqlCondition: {
        sParentId: sId,
      },
      bFilter: [{
        bFilterName: 'sPeriodId',
        bFilterValue: iYear,
        bFilterCondition: 'like',
      }],
    };
    const dataUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${financeId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url: dataUrl, sTabId, componentName, value, formRoute: '/sysaccountperiod', returnType: 'data',
      },
    });
    /* 获取表头 */
    const headerConfig = [];
    for (const child of financeConfig) {
      if (child.sName !== '' && child.bVisible && child.showName !== '') {
        headerConfig.push({
          title: child.showName,
          dataIndex: child.sName,
          width: child.iFitWidth,
        });
      }
    }
    this.setState({ headerConfig, financeConfig, financeId });
  }

  componentWillReceiveProps(nextProps) {
    const { disabled, content, iYear } = nextProps;
    const { dataList } = content;
    const {
      sDataListTabId, returnType, loading, componentName, urlData,
    } = dataList;
    if (this.state.sTabId === sDataListTabId && this.state.sTabId === nextProps.app.currentPane.key
      && this.state.componentName === componentName) {
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      if (returnType === 'data') {
        if (componentName === 'elecustomercontacts') {
          this.setState({ disabled });
        }
        if (loading === false) {
          this.setState({ loading: false });
        }
        if (componentName === 'sysaccountperiod') {
          const finDisabled = urlData.length > 0;
          this.setState({ finDisabled });
        }
      }
    }
    this.setState({ disabled, iYear });
  }

  shouldComponentUpdate(nextProps) {
    const { componentName } = nextProps;
    let flag = true;
    if (nextProps.disabled !== this.state.disabled) {
      return true;
    }
    /* 弹窗数据回显需要刷新列表 */
    if (nextProps.refreshList) {
      return true;
    }
    if (nextProps.disabled === this.state.disabled && nextProps.disabled === false) {
      return false;
    }
    if (this.state.sTabId === nextProps.app.currentPane.key &&
      this.state.componentName === componentName) {
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  /* 用于返回列表编辑框弹窗所属行主键 */
  handleRecordKey = (key) => {
    this.props.handleRecordKey({ accountDataKey: key });
  };

  handleChange = (value) => {
    this.props.oniYear(value);
  };

  tEndDate = (iYear, month, days) => {
    let tEndDate = '';
    let day = '';
    if (days !== '1') {
      day = (days * 1) - 1;
    } else if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
      day = 31;
    } else if (month === 2) {
      if (this.handleIsLeapYear(iYear)) {
        day = 29;
      } else {
        day = 28;
      }
    } else {
      day = 30;
    }
    if (days === '1') {
      tEndDate = `${iYear}-${month}-${day}`;
    } else if (month <= 11) {
      tEndDate = `${iYear}-${month + 1}-${day}`;
    } else {
      tEndDate = `${iYear + 1}-1-${day}`;
    }
    return tEndDate;
  };

  handleIsLeapYear = (Year) => {
    if ((((Year % 4) === 0) && ((Year % 100) !== 0)) || ((Year % 400) === 0)) {
      return (true);
    } else { return (false); }
  };

  handleClick = () => {
    /* 获取唯一Id */
    const newRowList = [];
    let keys = [];
    const { token } = this.props.app;
    const url = `${config.server_host}getUuid/12`;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    const showConfigList = this.state.financeConfig;
    const newData = {};
    const { iYear } = this.state;
    const day = this.state.tTabStartDate;
    this.state.headerConfig.forEach((slaveChild) => {
      const ckey = slaveChild.dataIndex;
      const showConfig = showConfigList.filter(item => (item.sName === ckey))[0];
      if (ckey !== 'iOrder' || ckey !== 'sPeriodId' || ckey !== 'tStartDate' || ckey !== 'tEndDate') {
        const columnValue = commonFunc.listDefaultValueNewAdd(showConfig, '');
        newData[ckey] = columnValue;
      }
    });
    fetch(url, options).then(response => response.json()).then((json) => {
      keys = json.dataset.rows;
      for (let i = 0; i < keys.length; i += 1) {
        newData.key = keys[i];
        const month = i + 1;
        newData.iOrder = month;
        newData.sPeriodId = month <= 9 ? `${iYear}0${month}` : `${iYear}${month}`;
        newData.tStartDate = `${iYear}-${month}-${day}`;
        const tEndDate = this.tEndDate(iYear, month, day);
        newData.tEndDate = tEndDate;
        newRowList.push({ ...newData, handleType: 'add' });
      }
      this.props.handleAccountData(newRowList);
    });
  };

  handleOptions = () => {
    const options = [];
    for (let i = 1; i < 29; i += 1) {
      options.push(<Option key={i}>{i}</Option>);
    }
    return options;
  };

  handleChange = (value) => {
    this.props.oniYear(value);
    const {
      sId, financeId, sActiveId, sTabId, componentName,
    } = this.state;
    const { dispatch } = this.props;
    const values = {
      sSqlCondition: {
        sParentId: sId,
      },
      bFilter: [{
        bFilterName: 'sPeriodId',
        bFilterValue: value,
        bFilterCondition: 'like',
      }],
    };
    const dataUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${financeId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url: dataUrl, sTabId, componentName, value: values, formRoute: '/sysaccountperiod', returnType: 'data',
      },
    });
  };

  handleOptionChange = (value) => {
    this.setState({ tTabStartDate: value });
  };


  render() {
    const {
      app, form, handleAccountData, dataExist, dataName, dataType, handleModalPane, dataList, onSlaveAdd, onClose,
    } = this.props;
    const {
      iYear, headerConfig, financeConfig, sActiveId, loading, finDisabled,
    } = this.state;
    const { handleRecordKey } = this;
    const staticEditProps = {
      sActiveId,
      showConfigList: financeConfig,
      headerConfig,
      dataListAll: dataExist ? dataList : [],
      handleTableData: handleAccountData,
      handleRecordKey, /* 用于返回列表编辑框弹窗所属行主键 */
      app,
      form,
      dataName,
      dataType,
      handleModalPane,
      btnAddShow: false,
      btnDelShow: false,
      disabled: true,
      onClose,
      onSlaveAdd,
    };
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 15 } };
    return (
      <Spin spinning={loading}>
        <FormItem className={styles.searchSlaveForm}>
          <div className={styles.tableOptionSys}>
            <Row style={{ marginBottom: 15 }}>
              <Col span={24}>
                <Col span={6}>
                  <FormItem
                    {...formItemLayout}
                    label="年度"
                  >
                    <InputNumberA defaultValue={iYear} onChange={this.handleChange} />
                  </FormItem>
                </Col>
                <Col span={6}>
                  <FormItem
                    {...formItemLayout}
                    label="起始时间"
                  >
                    <Select defaultValue="1" style={{ width: 120 }} onChange={this.handleOptionChange} disabled={finDisabled}>
                      {this.handleOptions()}
                    </Select>
                  </FormItem>
                </Col>
                <Col span={6}>
                  <Button onClick={this.handleClick} disabled={finDisabled}>默认值</Button>
                </Col>
              </Col>
            </Row>
            <StaticEditTable {...staticEditProps} />
          </div>
        </FormItem>
      </Spin>
    );
  }
}

export default TabFinancePeriodComponent;

